package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.result.CustomizeException;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {
        //根据id删除分类，如果关联了菜品就不删除
        LambdaQueryWrapper<Dish> dishLQW = new LambdaQueryWrapper<>();
        dishLQW.eq(Dish::getCategoryId, id);
        int dishCount = dishService.count(dishLQW);
        if (dishCount > 0 ) {
            //抛出异常，提示该分类下面已有菜品
            throw new CustomizeException("该分类下面已有菜品,不能删除!");
        }

        //根据id删除分类，如果关联了套餐就不删除
        LambdaQueryWrapper<Setmeal> setmealLQW = new LambdaQueryWrapper<>();
        setmealLQW.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealLQW);
        if (setmealCount > 0) {
            //抛出异常，提示该分类下已有套餐
            throw new CustomizeException("该分类下面已有套餐,不能删除!");
        }

        //删除该分类
        this.removeById(id);
    }
}
